package com.liangyu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.liangyu.core.ResultCode;
import com.liangyu.core.ResultList;
import com.liangyu.dto.FileResultDto;
import com.liangyu.service.FileServerService;
import com.liangyu.util.ApiUserUtils;
import com.liangyu.util.CommonUtil;
import com.liangyu.util.FileUtil;
import com.liangyu.util.StringUtil;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FileServerServiceImpl implements FileServerService {

    private static Logger log = LoggerFactory.getLogger(FileServerServiceImpl.class);

    //文件上传路径    @Service包含@Component
    @Value("${global-config.filePath}")
    private String filepath;
    //是否开启
    @Value("${global-config.imgCompressPic}")
    private boolean imgCompressPic;
    //宽
    @Value("${global-config.outputWidth}")
    private int outputWidth;
    //高
    @Value("${global-config.outputHeight}")
    private int outputHeight;

    @Value("${server.port}")
    private String port;

//    @Autowired
//    ApiUserUtils apiUserUtils;

    //必须注入，不可以创建对象，否则配置文件引用的路径属性为null
    @Autowired
    FileUtil fileUtil;

    @Transactional
    @Override
    public ResultList fileUpload(MultipartFile[] file, String ty) {
//        String str = FileUploadConstant.getFileUploadConstant(ty) != "" ? FileUploadConstant.getFileUploadConstant(ty) + "/" : "";

        String filepathType = filepath;
        //保存各种信息
        ResultList resultMap = new ResultList();
        List<String> fileName = new ArrayList<String>();
        HttpServletRequest request = null;
        HttpServletResponse response;
        List<FileResultDto> list = new ArrayList<>();
        if (file != null && file.length > 0) {
            PrintWriter out = null;
            //图片上传
            try {
                for (int i = 0; i < file.length; i++) {
                    if (!file[i].isEmpty()) {
                        //上传文件，随机名称，","分号隔开
                        fileName.add(fileUtil.uploadImage(request, filepathType, file[i], true) + fileUtil.getRealName());
                        String origName = fileUtil.getOrigName();
                        String realName = fileUtil.getRealName();
                        Long fileSize = fileUtil.getFileSize();
                        String suffix = fileUtil.getSuffix();
                        FileResultDto fileResultDto = new FileResultDto();
                        fileResultDto.setFileName(origName);
                        fileResultDto.setFileMaskName(realName);
                        fileResultDto.setFilePath("/files/" + realName);

                        //ip+prot+files/fileName
                        //fileResultDto.setDownloadPath();
                        fileResultDto.setFileSize(fileSize);
                            /*//文件类型
                            String type = file[i].getContentType();
                            String suffix = "";         //后缀名
                            if(type!=null&&type.split("/").length>1){
                                suffix = type.split("/")[1];
                            }*/
                        fileResultDto.setSuffix(suffix.toLowerCase());
                        list.add(fileResultDto);
                    }
                }
                //上传成功
                if (fileName != null && fileName.size() > 0) {

                    log.info("上传成功");
                    resultMap.setRows(list);
                    resultMap.setCode(ResultCode.SUCCESS);
                    resultMap.setMessage("上传成功！");
                } else {
                    resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
                    resultMap.setMessage("上传失败！文件格式错误！");
                }
            } catch (Exception e) {
                e.printStackTrace();
                resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
                resultMap.setMessage("上传异常");
            }
            System.out.println("==========filename==========" + fileName);
        } else {
            resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
            resultMap.setMessage("没有检测到有效文件！");
        }
        return resultMap;
    }

    @Override
    public List<FileResultDto> getFileInfoList(List<MultipartFile> files) {
        if (files != null && files.size() > 0) {

        }
        return null;
    }

//    @Transactional
//    @Override
//    public ResultList uploadImg(MultipartFile[] file, String ty) {
//        String accessToken = "";
//        //获取openid
//        String requestUrl = apiUserUtils.getAccessToken();//通过自定义工具类组合出小程序需要的登录凭证 code
//        log.info("》》》组合token为：" + requestUrl);
//        JSONObject sessionData = CommonUtil.httpsRequest(requestUrl, "GET", null);
//        if (null != sessionData && !StringUtils.isNullOrEmpty(sessionData.getString("access_token"))) {
//            accessToken = sessionData.getString("access_token");
//        }
//        String filepathType = filepath;
//        //保存各种信息
//        //按日期分文件夹
//        String dataForm = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        ResultList resultMap = new ResultList();
//        List<String> fileName = new ArrayList<String>();
//        HttpServletRequest request = null;
//        HttpServletResponse response;
//        List<FileResultDto> list = new ArrayList<>();
//        if (file != null && file.length > 0) {
//            //图片上传
//            try {
//                for (int i = 0; i < file.length; i++) {
//                    //上传文件，随机名称，","分号隔开
//                    fileName.add(fileUtil.uploadImg(request, filepathType, file[i], true) + fileUtil.getOrigName());
//                    if (!file[i].isEmpty()) {
//                        //imageIO.read(arg);图片解析,可传入文件,文件输入流等
//                        Image img = ImageIO.read(new File(filepathType + fileUtil.getOrigName()));
//                        if (img == null) {
//                            resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
//                            resultMap.setMessage("上传失败！文件格式错误！");
//                            return resultMap;
//                        }
//                        String origName = fileUtil.getOrigName();
//                        String oldName = fileUtil.getOldName();
//                        Long fileSize = fileUtil.getFileSize();
//                        FileResultDto fileResultDto = new FileResultDto();
//                        fileResultDto.setFileName(oldName);
//                        //判断是否存在目录
//                        if (imgCompressPic) {
//                            File targetFile = new File(filepath + "/img/", origName);
//                            if (!targetFile.exists()) {
//                                targetFile.getParentFile().mkdirs();//创建目录
//                            }
//                            if (ImgUtil.compressPic(filepathType, origName, outputWidth, outputHeight))
//                                fileResultDto.setFilePath("/files/" + "img/" + origName);
//                            else
//                                fileResultDto.setFilePath("/files/" + origName);
//                        } else {
//                            fileResultDto.setFilePath("/files/" + origName);
//                        }
//                        fileResultDto.setFileMaskName(origName);
//                        fileResultDto.setFileSize(fileSize);
//                        String suffix1 = StringUtil.spiltRtoL(oldName);
//                        String s = suffix1.substring(0, suffix1.indexOf(".") + 1);
//                        fileResultDto.setSuffix(StringUtil.spiltRtoL(s));
//                        list.add(fileResultDto);
//                        String filePath = filepath + fileResultDto.getFilePath().replace("/files", "");
//                        InputStream inputStream = new FileInputStream(filePath);
//                        if (!checkPic(inputStream, accessToken, file[i].getContentType())) {
//                            resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
//                            resultMap.setMessage("存在敏感信息,上传失败！");
////                            inputStream.close();
//                            for (FileResultDto resultDto : list) {
//                                try {
//                                    FileUtils.forceDelete(new File(filepath + resultDto.getFilePath().replace("/files", "")));
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                            return resultMap;
//                        }
//                    }
//                }
//                //上传成功
//                if (fileName != null && fileName.size() > 0) {
//                    log.info("上传成功");
//                    resultMap.setRows(list);
//                    resultMap.setCode(ResultCode.SUCCESS);
//                    resultMap.setMessage("上传成功！");
//                } else {
//                    resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
//                    resultMap.setMessage("上传失败！文件格式错误！");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
//            }
//            System.out.println("==========filename==========" + fileName);
//        } else {
//            resultMap.setCode(ResultCode.FILE_UPLOAD_ERROR);
//            resultMap.setMessage("没有检测到有效文件！");
//        }
//
//
//        return resultMap;
//    }
//
//    /**
//     * 校验图片是否有敏感信息
//     *
//     * @param inputStream
//     * @return
//     */
//    private static Boolean checkPic(InputStream inputStream, String accessToken, String contentType) throws IOException {
//        try {
//            CloseableHttpClient httpclient = HttpClients.createDefault();
//            CloseableHttpResponse response = null;
//            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken);
//            request.addHeader("Content-Type", "application/octet-stream");
////            InputStream inputStream = multipartFile.getInputStream();
//            byte[] byt = new byte[inputStream.available()];
//            inputStream.read(byt);
//            request.setEntity(new ByteArrayEntity(byt, ContentType.create(contentType)));
//            response = httpclient.execute(request);
//            HttpEntity httpEntity = response.getEntity();
//            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
//
//            System.out.println("==========result==========" + result);
//            JSONObject jso = JSONObject.parseObject(result);
//            return getResult(jso);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return true;
//        }finally {
//            inputStream.close();
//        }
//    }

    /**
     * 返回状态信息,可以修改为自己的逻辑
     *
     * @param jso
     * @return
     */
    private static Boolean getResult(JSONObject jso) {
        Object errcode = jso.get("errcode");
        int errCode = (int) errcode;
        if (errCode == 0) {
            return true;
        } else if (errCode == 87014) {
            return false;
        } else {
            return false;
        }
    }


    @Transactional
    @Override
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, String fileUrl) {
        /*  String filePath = fileUrl.split("-")[0];  http://127.0.0.1:8080/files/20190711%E7%AE%A1%E7%90%86%E5%91%98%E7%AE%A1%E7%90%86.jpg*/
        String filePath = filepath;
        String fileName = fileUrl.split("/")[4]; //文件名称
        if (fileName != null) {
            //设置文件路径
            File file = new File(filePath + fileName);  //下载路径：http://localhost:8080/files/xxx.txt
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download;charset=UTF-8");// 设置强制下载不打开
                try {
                    response.addHeader("Content-Disposition", "attachment; fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

    /*@Transactional
    @Override
    public int importXls(MultipartFile file) {
        *//*HttpServletRequest request = null;
        List<String> fileName =new ArrayList<String>();
        fileName.add(fileUtil.uploadImage(request, filepath, file, true)+ fileUtil.getOrigName());
        String path = fileName.get(0);
        return path;*//*

        Workbook wb =null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String,String>> list = null;
        String cellData = null;
        String filePath = "D:\\test.xlsx";
        String columns[] = {"name","age","score"};
        wb = ExcelUtils.readExcel(filePath);
        if(wb != null){
            //用来存放表中数据
            list = new ArrayList<Map<String,String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i<rownum; i++) {
                Map<String,String> map = new LinkedHashMap<String,String>();
                row = sheet.getRow(i);
                if(row !=null){
                    for (int j=0;j<colnum;j++){
                        cellData = (String) ExcelUtils.getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                }else{
                    break;
                }
                list.add(map);
            }
        }
        return  0 ;
    }*/
}
